<template>
    <div>
        <n-alert v-if="alertShow" :title="title" :type="type" :bordered="false">
            <div v-if="isLoading" class="loading-container">
                <n-spin size="small" type="info" stroke-width="10" stroke="#2080f0"/>
                <span class="loading-text">&nbsp;正在验证资源配置，请稍候...</span>
            </div>
            <div v-else>
                {{ errMsg }}
            </div>
        </n-alert>
        <n-form
            style="margin-top: 24px"
            ref="formRef"
            :model="form"
            :rules="rules"
            label-placement="left"
            label-width="120"
            require-mark-placement="right-hanging"
            :disabled="formDisabled"
        >
            <n-form-item label="资源类型" path="type">
                <n-select v-model:value="form.type" placeholder="请选择资源类型" :options="mcpResourceOptions"
                          @update:value="handleTypeChange">
                </n-select>
            </n-form-item>

            <n-form-item label="资源名称" path="name">
                <n-input v-model:value="form.name" placeholder="请输入资源名称"></n-input>
            </n-form-item>

            <!-- 本地资源配置项 -->
            <template v-if="form.type === 1">
                <n-form-item label="命令" path="command">
                    <n-input v-model:value="form.command" placeholder="请输入命令"></n-input>
                </n-form-item>

                <n-form-item label="参数" path="args">
                    <n-dynamic-input v-model:value="form.args" placeholder="请输入参数">
                        <template #create-button-default>
                            添加参数
                        </template>
                    </n-dynamic-input>
                </n-form-item>

                <n-form-item label="环境变量" path="env">
                    <n-card size="small" class="env-card">
                        <template #header>
                            <div class="env-header">
                                <span>环境变量配置</span>
                                <n-button size="small" type="primary" ghost @click="addEnvVar">
                                    添加环境变量
                                </n-button>
                            </div>
                        </template>
                        <div v-for="(v, index) in envVars" :key="index" class="env-item">
                            <n-input v-model:value="v.key" placeholder="变量名" class="env-key-input" />
                            <n-input v-model:value="v.value" placeholder="变量值" class="env-value-input"/>
                            <jb-btn circle size="small" type="error" @click="removeEnvVar(index)" :icon="Icons.DELETE">

                            </jb-btn>
                        </div>
                        <div v-if="envVars.length === 0" class="no-env-vars">
                            还没有添加环境变量
                        </div>
                    </n-card>
                </n-form-item>
            </template>

            <!-- 远程资源配置项 -->
            <template v-else-if="form.type === 2">
                <n-form-item label="URL" path="url">
                    <n-input v-model:value="form.url" placeholder="请输入URL"></n-input>
                </n-form-item>
            </template>

            <!-- 检测配置 -->
            <n-form-item label="检测配置">
                <jb-btn type="primary" ghost @click="check()" :loading="isLoading"
                        :disabled="isLoading" icon="">
                    <jb-icon icon="ri:shield-check-line" :local="true" width="20" color="#18a058"></jb-icon>
                    <span>&nbsp;检测当前配置是否正确</span>
                </jb-btn>
            </n-form-item>
        </n-form>
    </div>

</template>

<script setup>
import { onMounted, reactive, ref, watch } from 'vue'
import { JBoltApi } from '@/service/request'
import { useResetableData } from "@/hooks/common/use-resetable-data.js";
import {Icons} from "@/constants/index.js";

const props = defineProps({
    id: {
        type: String
    }
})

const formRef = ref(null)
const title = ref('资源配置正确')
const type = ref('success')
const errMsg = ref('')
const alertShow = ref(false)
const formDisabled = ref(false) // 表单禁用状态
const isLoading = ref(false)

const form = ref({
    id: '',
    name: '',
    type: null,
    command: '',
    args: [],
    url: '',
    enable: true,
    createTime: ''
})

// 单独管理环境变量，方便增删改
const envVars = ref([])

// 添加环境变量
function addEnvVar() {
    envVars.value.push({key:'', value:''})
}


// 删除环境变量
function removeEnvVar(index) {
    if (index !== -1) {
        envVars.value.splice(index, 1)
    }
}

const rules = reactive({
    type: {
        required: true,
        message: '请选择资源类型',
        trigger: 'change',
        validator: (rule, value) => {
            return value === 1 || value === 2 || new Error('请选择资源类型')
        }
    },
    name: {
        required: true,
        message: '请输入资源名称',
        pattern: /\S/, // 至少有一个非空白字符
        trigger: 'change'
    },
    command: {
        required: true,
        message: '请输入命令',
        trigger: 'blur',
        validator: (rule, value) => {
            if (form.value.type === 1 && (!value || !value.trim())) {
                return new Error('请输入命令')
            }
            return true
        }
    },
    url: {
        required: true,
        message: '请输入URL',
        trigger: 'blur',
        validator: (rule, value) => {
            if (form.value.type === 2 && (!value || !value.trim())) {
                return new Error('请输入URL')
            }
            return true
        }
    }
})

// 加载编辑数据
function loadEditData() {
    if (props.id) {
        formDisabled.value = true
        JBoltApi.tryGet(`/mcpResource/getById/${props.id}`).then(res => {
            if (res.data) {
                form.value.id = res.data.id
                form.value.name = res.data.name
                form.value.type = res.data.type
                form.value.enable = res.data.enable
                form.value.createTime = res.data.createTime

                // 解析配置信息
                if (res.data.config) {
                    try {
                        const config = res.data.config
                        if (form.value.type === 1) { // 本地资源
                            form.value.command = config.command || ''
                            form.value.args = config.args || []

                            // 处理环境变量
                            if (config.env) {
                                Object.keys(config.env).forEach((key, index) => {
                                    envVars.value.push({key, value: config.env[key]})
                                })
                            }
                        } else if (form.value.type === 2) { // 远程资源
                            form.value.url = config.url || ''
                        }
                    } catch (error) {
                        console.error('解析配置信息失败:', error)
                    }
                }
            }
            formDisabled.value = false
        }).catch(error => {
            console.error(error)
            formDisabled.value = false
        })
    }
}

async function submit(callback) {
    await formRef.value?.validate();
    let submitData = {
        id: form.value.id,
        name: form.value.name,
        type: form.value.type,
        enable: form.value.enable
    }

    // 根据类型处理配置信息
    if (form.value.type === 1) { // 本地资源
        let envValue = {};
        envVars.value?.forEach(item => {
            envValue[item.key] = item.value
        })
        submitData = { ...submitData,
            command: form.value.command,
            args: form.value.args || [],
            env: envValue
        }
    } else if (form.value.type === 2) { // 远程资源
        submitData = {...submitData,
            url: form.value.url
        }
    }

    const url = form.value.id ? '/mcpResource/update' : '/mcpResource/add'
    await JBoltApi.tryPost(url, submitData).then(res => {
        if (callback) {
            callback()
        }
    }).catch(error => {
        console.error(error)
    })
    return true;
}

// 检查资源配置
function check() {
    formRef.value?.validate(errors => {
        if (errors) {
            return
        }

        isLoading.value = true
        alertShow.value = false

        let checkData = {
            type: form.value.type,
            name: form.value.name,
        }

        // 根据类型处理配置信息
        if (form.value.type === 1) { // 本地资源
            let envValue = {};
            envVars.value?.forEach(item => {
                envValue[item.key] = item.value
            })
            checkData = { ...checkData,
                command: form.value.command,
                args: form.value.args || [],
                env: envValue
            }
        } else if (form.value.type === 2) { // 远程资源
            checkData = {...checkData,
                url: form.value.url
            }
        }

        JBoltApi.tryPost('/mcpResource/check', checkData, {
            timeout: 30000
        }).then(res => {
            isLoading.value = false
            alertShow.value = true
            title.value = '资源配置正确'
            type.value = 'success'
            errMsg.value = '资源配置检测通过'
        }).catch(error => {
            isLoading.value = false
            alertShow.value = true
            title.value = '资源配置错误'
            type.value = 'error'
            errMsg.value = error.message || '资源配置检测失败'
            console.error(error)
        })
    })
}

function handleTypeChange(value) {
    console.debug(value)
    // 切换资源类型时重置相关字段
    if (value === 1) { // 本地资源
        form.value.url = ''
    } else if (value === 2) { // 远程资源
        form.value.command = ''
        form.value.args = []
        // 清空环境变量
        Object.keys(envVars).forEach(key => {
            delete envVars[key]
        })
        envKeys.value = []
    }
}

const mcpResourceOptions = [
    { label: '本地资源', value: 1 },
    { label: '远程资源', value: 2 }
]

onMounted(() => {
    if (props.id) {
        loadEditData()
    }
})

defineExpose({
    submit
})
</script>

<style scoped>
.loading-container {
    display: flex;
    align-items: center;
}

.loading-text {
    margin-left: 8px;
}

.env-card {
    width: 100%;
}

.env-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
}

.env-item {
    display: flex;
    margin-bottom: 8px;
    align-items: center;
}

.env-key-input {
    flex: 1;
    margin-right: 8px;
}

.env-value-input {
    flex: 2;
    margin-right: 8px;
}

.env-delete-button {
    flex-shrink: 0;
}

.no-env-vars {
    color: #999;
    text-align: center;
    padding: 16px 0;
}
</style>
